package com.javaee.interceptor;




import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserIntercpter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());
        String username = (String) request.getSession().getAttribute("username");
        HttpSession session = request.getSession();
        if(url.contains("/index.jsp")
                ||url.contains("/register.jsp")
                ||url.contains("/login")
                ||url.contains("/register")
                ||url.contains(".png")
                ||url.contains(".jpg")) {
            System.out.println(url + "这是登录入口或者静态资源，放行");
            filterChain.doFilter(request, response);
        }else if (StringUtils.isNotBlank(username))
        {
            System.out.println("用户已经登陆，放行");
            filterChain.doFilter(request, response);
        }
        else {
            request.getRequestDispatcher("404.jsp").forward(request, response);
        }
    }
}
